﻿@using SmartStore.Core.Domain.DataExchange;
@using SmartStore.Admin.Models.DataExchange;
@model ImportProfileListModel
@{
	ViewBag.Title = T("Common.Import").Text;
}

<div class="section-header">
    <div class="title">
		<i class="fa fa-download"></i>
        @T("Common.Import")
    </div>
    <div class="options">
        <a href="javascript:void(0)" data-url="@Url.Action("Create")" class="btn btn-primary import-profile-button">
			<i class="fa fa-plus"></i>
			<span>@T("Admin.Common.AddNew")</span>
		</a>
    </div>
</div>

@if(Model.Profiles.Any())
{
	<div class="table-responsive">
		<table id="import-profile-list" class="table admin-table">
			<thead>
				<tr>
					<th>@T("Admin.DataExchange.Import.Name")</th>
					<th>@T("Admin.Common.Entity")</th>
					<th>@T("Admin.Common.ImportFiles")</th>
					<th>@T("Admin.DataExchange.Import.LastImportResult")</th>
					<th>@T("Admin.System.ScheduleTasks.LastStart")</th>
					<th>@T("Admin.System.ScheduleTasks.NextRun")</th>
					<th>@T("Admin.Common.Actions")</th>
				</tr>
			</thead>
			<tbody>
				@foreach (var profile in Model.Profiles)
				{
					<tr data-profile-id="@profile.Id" data-task-id="@profile.ScheduleTaskId" class="@(profile.Enabled ? "" : "disabled")">
						<td>
							<a href="@Url.Action("Edit", new { id = profile.Id })"><strong>@profile.Name</strong></a>
						</td>
						<td>
							@profile.EntityTypeName
						</td>
						<td>
							@if (profile.ExistingFiles.Any())
							{
								<ul class="fa-ul mb-0 ml-0">
									@foreach (var file in profile.ExistingFiles.Where(x => !x.RelatedType.HasValue))
									{
										<li title="@file.Name">
											@Html.IconForFileExtension(file.Extension, false)
											<a href="@Url.Action("DownloadImportFile", new { id = profile.Id, name = file.Name })" download>@file.Name</a>
										</li>
									}
								</ul>
							}

						</td>
						<td id="ProfileImportResult@(profile.Id)">
							@if (profile.ImportResult != null)
							{
								Html.RenderPartial("ProfileImportResult", profile.ImportResult);
							}
							else
							{
								<span class="muted">@("".NaIfEmpty())</span>
							}
						</td>
						<td>
							<div class="last-run-info">
								@{ Html.RenderPartial("~/Administration/Views/ScheduleTask/_LastRun.cshtml", profile.TaskModel); }
							</div>
						</td>
						<td class="progress-info">
							<div class="next-run-info">
								@{ Html.RenderPartial("~/Administration/Views/ScheduleTask/_NextRun.cshtml", profile.TaskModel); }
							</div>
							<div class="task-progress text-muted@(profile.IsTaskRunning ? "" : " d-none")" data-task-id="@profile.ScheduleTaskId" data-running="@(profile.IsTaskRunning ? "true" : "false")"></div>
						</td>
						<td style="width: 200px;" align="right" class="omega">
							<button type="button" class="btn btn-block btn-sm btn-warning btn-run-task@(profile.IsTaskRunning || !profile.Enabled ? " d-none" : "")"
									data-url="@Url.Action("Execute", "Import", new { area = "Admin", id = @profile.Id })" data-task-id="@profile.ScheduleTaskId">
								<i class="fa fa-play"></i>
								<span>@T("Admin.System.ScheduleTasks.RunNow")</span>
							</button>

							<a href="@Url.Action("CancelJob", "ScheduleTask", new { id = profile.ScheduleTaskId })" class="btn btn-block btn-sm btn-secondary btn-cancel-task@(!profile.IsTaskRunning ? " hide" : "")"
							   data-task-id="@profile.ScheduleTaskId" onclick='return confirm(@T("Admin.Common.AreYouSure").JsText);'>
								<span>@T("Common.Cancel")</span>
							</a>

							<a href="@Url.Action("DownloadLogFile", new { id = profile.Id })" target="LogFile"
							   class="btn btn-secondary btn-sm btn-block btn-log@(profile.IsTaskRunning || !profile.Enabled || !profile.LogFileExists ? " d-none" : "")">
								<i class="far fa-file-alt"></i>
								<span>@T("Admin.Configuration.ActivityLog")</span>
							</a>
						</td>
					</tr>
				}
			</tbody>
		</table>
	</div>
}
else
{
	<div class="alert alert-info alert-dismissible">
		@T("Admin.DataExchange.Import.NoProfiles")
		<button type="button" class="close" data-dismiss="alert">&times;</button>
	</div>
}

@{Html.SmartStore().Window()
	.Name("import-profile-dialog")
	.Title(T("Common.Profile") + " - " + T("Admin.Common.AddNew"))
	.HtmlAttribute("data-profile", T("Common.Profile").Text)
	.Content(@<text>
        <form method="POST" action="@Url.Action("Create", "Import", new { area = "Admin" })" class="import-profile-form">
			<p class="text-muted">
				@T("Admin.DataExchange.Import.ProfileCreationNote")
			</p>
			<div>
				<div class="form-group">
					@Html.SmartLabelFor(x => x.EntityType)
					@Html.DropDownListFor(x => x.EntityType, Model.AvailableEntityTypes)
				</div>

				<div id="ImportFileUploadContainer">
					<input type="hidden" name="TempFileName" />
					@(Html.SmartStore().FileUploader()
						.Name("ImportFileUploader")
						.UploadUrl(Url.Action("FileUpload", new { id = Model.Id }))
						.AcceptedFileTypes("csv|xlsx|txt|tab")
						.ShowRemoveButton(false)
						.ShowRemoveButtonAfterUpload(false)
						.UploadText(T("Admin.DataExchange.Import.FileUpload").Text)
						.OnUploadCompletedHandlerName("onUploadCompleted")
					)
				</div>

				<div id="ImportFileList" class="hide">
					&nbsp;
				</div>
			</div>
        </form>
	</text>)
	.FooterContent(@<text>
		<button class="btn btn-secondary btn-flat" data-dismiss="modal">@T("Common.Cancel")</button>
		<button type="button" class="btn btn-primary" disabled="disabled">@T("Common.OK")</button>
	</text>)
	.Render();
}

<script>
	window['onUploadCompleted'] = function (e, el, data) {
		if (!_.isEmpty(data.result.tempFile)) {
			$('#import-profile-dialog').find('input[name=TempFileName]').val(data.result.tempFile);
			$('#ImportFileList').html(data.result.tempFile).show();
			$('#ImportFileUploadContainer').hide();		// just one initial file to specify the file type
			$('#import-profile-dialog').find('.btn-primary').prop('disabled', false);
		}
		else if (!_.isEmpty(data.result.error)) {
			$('#ImportFileList').html('<div class="alert alert-danger">' + data.result.error + '</div>').show();
		}
	}

	jQuery(document).ready(function () {

		// show profile dialog
		$(document).on('click', '.import-profile-button', function (e) {
			e.preventDefault();
			$('#import-profile-dialog').modal('show');
			return false;
        });

		// submit dialog form
        $('#import-profile-dialog').on('click', '.btn-primary', function () {
			$('#import-profile-dialog').find('.import-profile-form').submit();
		});

		// start task
		$(document).on('click', '.btn-run-task', function (e) {
			e.preventDefault();
			$(this).doPostData({
				ask: @T("Admin.Common.AskToProceed").JsText
			});
			return false;
		});

		SmartStore.Admin.TaskWatcher.startWatching({
			context: $('#import-profile-list'),
			elementsSelector: '.task-progress',
			defaultProgressMessage: @T("Admin.System.ScheduleTasks.RunNow.IsRunning").JsText,
			pollUrl: '@Url.Action("GetRunningTasks", "ScheduleTask")',
			onTaskStarted: function (task, el) {
				var tr = el.closest('tr');
				tr.find('.btn-run-task').addClass('hide');
				tr.find('.btn-cancel-task').removeClass('hide');
				tr.find('.btn-log').addClass('hide');
				tr.find('.next-run-info').addClass('hide');
			},
			onTaskCompleted: function (taskId, el) {
				var tr = el.closest('tr'),
					profileId = tr.data('profile-id');

				tr.find('.btn-run-task').removeClass('hide');
				tr.find('.btn-cancel-task').addClass('hide');
				tr.find('.btn-log').removeClass('hide');

				$.ajax({
					cache: false,
					global: false,
					type: 'POST',
					url: '@Url.Action("GetTaskRunInfo", "ScheduleTask")',
					data: { id: taskId },
					success: function (data) {
						tr.find('.next-run-info').html(data.nextRunHtml).removeClass("hide");
						tr.find('.last-run-info').html(data.lastRunHtml);
					}
				});

				$.get('@Url.Action("ProfileListDetails")?profileId=' + profileId, function (response) {
					$('#ProfileImportResult' + profileId).html(response.importResult || '');
				});
			}
		});
	});
</script>
